package com.jbwz.web.generator.engine;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class CustomEngine extends VelocityTemplateEngine {
  private static final String VO_PACKAGE = File.separator + "vo";
  private static final String VO_TEMPLATE_PATH = "/templates/vo.java";

  public AbstractTemplateEngine batchOutput() {
    try {
      ConfigBuilder config = this.getConfigBuilder();
      List<TableInfo> tableInfoList = config.getTableInfoList();
      tableInfoList.forEach(
          tableInfo -> {
            Map<String, Object> objectMap = this.getObjectMap(config, tableInfo);
            Optional.ofNullable(config.getInjectionConfig())
                .ifPresent(t -> t.beforeOutputFile(tableInfo, objectMap));
            // VO.java
            outputVO(tableInfo, objectMap);
            // Mp.java
            outputEntity(tableInfo, objectMap);
            // mapper and xml
            outputMapper(tableInfo, objectMap);
            // service
            outputService(tableInfo, objectMap);
            // MpController.java
            outputController(tableInfo, objectMap);
          });
    } catch (Exception e) {
      throw new RuntimeException("无法创建文件，请检查配置信息！", e);
    }
    return this;
  }

  protected void outputVO(TableInfo tableInfo, Map<String, Object> objectMap) {
    String voName = tableInfo.getEntityName() + "VO";
    String entityPath = getPathInfo(OutputFile.entity) + VO_PACKAGE;
    if (StringUtils.isNotBlank(voName) && StringUtils.isNotBlank(entityPath)) {
      getTemplateFilePath(template -> VO_TEMPLATE_PATH)
          .ifPresent(
              (templatePath) -> {
                String entityFile =
                    String.format((entityPath + File.separator + "%s" + suffixJavaOrKt()), voName);
                outputFile(new File(entityFile), objectMap, templatePath);
              });
    }
  }
}
